<?php

/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2016-01-20
 * 版    本：1.0.0
 * 功能说明：用户控制器。
 *
 * */

namespace Qwadmin\Controller;

class MemberController extends ComController {

    public function index() {

        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $field = isset($_GET['field']) ? $_GET['field'] : '';
        $keyword = isset($_GET['keyword']) ? htmlentities($_GET['keyword']) : '';
        $order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
        $where = '';
		
        $prefix = C('DB_PREFIX');
        if ($order == 'asc') {
            $order = "{$prefix}member.t asc";
        } elseif (($order == 'desc')) {
            $order = "{$prefix}member.t desc";
        } else {
            $order = "{$prefix}member.uid desc";
        }
        if ($keyword <> '') {
            if ($field == 'user') {
                $where = "{$prefix}member.user LIKE '%$keyword%'";
            }
            if ($field == 'phone') {
                $where = "{$prefix}member.phone LIKE '%$keyword%'";
            }
            if ($field == 'qq') {
                $where = "{$prefix}member.qq LIKE '%$keyword%'";
            }
            if ($field == 'email') {
                $where = "{$prefix}member.email LIKE '%$keyword%'";
            }
        }
		if(!empty($where)){
			$where .= ' and ';
		}
		$where .= "{$prefix}member.pid=" . session('uid');
		
		$user_gid=$this->USER;//获取登陆账户的权限
		$UserJurisdiction=D("member")->getUserJurisdiction(session('uid')); 
		
        $user = M('member');
        $pagesize = 20; #每页数量
        $offset = $pagesize * ($p - 1); //计算记录偏移量
        $count = $user->where($where)->count('uid');

        $list = $user->field("{$prefix}member.*,{$prefix}auth_group.id as gid,{$prefix}auth_group.title")
                ->order($order)
                ->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}member.level")
                ->where($where)
                ->limit($offset . ',' . $pagesize)
                ->select();
		$html ='';
		$uid_arr = [];
		foreach($list as $key=>$value){
			$uid_arr[$value['uid']] = $key;
			$list[$key]['has_child'] = false;
			if($this->USER['level']<=2){
				$list[$key]['today_money'] = sprintf('%.2f', D("Income")->Income_today_count($value['uid'],$value['level']));
			}
		}
		//查询用户是否有下级
		if(count($uid_arr)>0){
			$pid_arr = M('member')->field("count(uid) as count_pid,pid")
								  ->where("pid in(" . implode(',',array_keys($uid_arr)) . ")")
								  ->group('pid')
								  ->select();
			foreach($pid_arr as $key => $value){
				$list[$uid_arr[$value['pid']]]['has_child'] = empty($value['count_pid']) ? false : true;
				
			}
		}
        //$user->getLastSql();
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
		//获取用户的锁定会员及其提现权限
		$this->assign('UserJurisdiction', $UserJurisdiction);
		$this->assign('login_gid', $user_gid['level']);
        $this->display();
    }
	/**
	* 获取一级渠道列表
	**/
	public function subindex() {

        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $field = isset($_GET['field']) ? $_GET['field'] : '';
        $keyword = isset($_GET['keyword']) ? htmlentities($_GET['keyword']) : '';
        $order = isset($_GET['order']) ? $_GET['order'] : 'DESC';
		$uid = I('get.uid', 0, 'intval');
        $where = '';
		
        $prefix = C('DB_PREFIX');
        if ($order == 'asc') {
            $order = "{$prefix}member.t asc";
        } elseif (($order == 'desc')) {
            $order = "{$prefix}member.t desc";
        } else {
            $order = "{$prefix}member.uid desc";
        }
        if ($keyword <> '') {
            if ($field == 'user') {
                $where = "{$prefix}member.user LIKE '%$keyword%'";
            }
            if ($field == 'phone') {
                $where = "{$prefix}member.phone LIKE '%$keyword%'";
            }
            if ($field == 'qq') {
                $where = "{$prefix}member.qq LIKE '%$keyword%'";
            }
            if ($field == 'email') {
                $where = "{$prefix}member.email LIKE '%$keyword%'";
            }
        }
		if(!empty($where)){
			$where .= ' and ';
		}
		if(empty($uid)){
			$where .= "{$prefix}member.level=3";
		}else{
			$where .= "{$prefix}member.pid={$uid}";
		}
		
		$user_gid=$this->USER;//获取登陆账户的权限
		$UserJurisdiction=D("member")->getUserJurisdiction(session('uid')); 
		
        $user = M('member');
        $pagesize = 20; #每页数量
        $offset = $pagesize * ($p - 1); //计算记录偏移量
        $count = $user->where($where)->count('uid');

        $list = $user->field("{$prefix}member.*,{$prefix}auth_group.id as gid,{$prefix}auth_group.title")
                ->order($order)
                ->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}member.level")
                ->where($where)
                ->limit($offset . ',' . $pagesize)
                ->select();
		
		$html ='';
		$uid_arr = [];
		$pid_list_arr = [];
		foreach($list as $key=>$value){
			$uid_arr[$value['uid']] = $key;
			if(!isset($pid_list_arr[$value['pid']])){
				$pid_list_arr[$value['pid']] = [];
			}
			$pid_list_arr[$value['pid']][] = $key;
			$list[$key]['has_child'] = false;
			if($this->USER['level']<=2){
				$list[$key]['today_money'] = sprintf('%.2f', D("Income")->Income_today_count($value['uid'],$value['level']));
			}
		}
		
		if(count($uid_arr)>0){
			//查询用户是否有下级
			$pid_arr = M('member')->field("count(uid) as count_pid,pid")
								  ->where("pid in(" . implode(',',array_keys($uid_arr)) . ")")
								  ->group('pid')
								  ->select();
			foreach($pid_arr as $key => $value){
				$list[$uid_arr[$value['pid']]]['has_child'] = empty($value['count_pid']) ? false : true;
				
			}
			//查询用户的上级
			$pid_arr = M('member')->field("user,uid")
								  ->where("uid in(" . implode(',',array_keys($pid_list_arr)) . ")")
								  ->group('uid')
								  ->select();
			
			foreach($pid_arr as $key => $value){
				foreach($pid_list_arr[$value['uid']] as $v){
					$list[$v]['p_user'] = $value['user'];
				}
			}
		}
        //$user->getLastSql();
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        $this->assign('list', $list);
        $this->assign('page', $page);
		//获取用户的锁定会员及其提现权限
		$this->assign('UserJurisdiction', $UserJurisdiction);
		$this->assign('login_gid', $user_gid['level']);
        $this->display();
    }
	/**
	* 获取下级列表
	**/
	public function childrenlist(){
		$uid = I("uid" , 0 , 'intval');
		if(empty($uid)){
			die('用户不能为空');
		}
		$field = isset($_GET['field']) ? $_GET['field'] : '';
        $keyword = isset($_GET['keyword']) ? htmlentities($_GET['keyword']) : '';
		
		$prefix = C('DB_PREFIX');
		$user_gid=D("member")->getUserGid(session('uid'));//获取登陆账户的权限
		$member_gid=D("member")->getUserGid($uid);//获取登陆账户的权限
		
		$UserJurisdiction=D("member")->getUserJurisdiction(session('uid')); 
		
		if ($keyword <> '') {
            if ($field == 'user') {
                $where = "{$prefix}member.user LIKE '%$keyword%'";
            }
            if ($field == 'phone') {
                $where = "{$prefix}member.phone LIKE '%$keyword%'";
            }
            if ($field == 'qq') {
                $where = "{$prefix}member.qq LIKE '%$keyword%'";
            }
            if ($field == 'email') {
                $where = "{$prefix}member.email LIKE '%$keyword%'";
            }
        }
		if(!empty($where)){
			$where .= ' and ';
		}
		$where .= "{$prefix}member.pid=" . $uid;
		
		$user = M('member');
        $list = $user->field("{$prefix}member.*,{$prefix}auth_group.id as gid,{$prefix}auth_group.title")
                ->order($prefix.'member.uid asc')
                ->join("{$prefix}auth_group ON {$prefix}auth_group.id = {$prefix}member.level")
                ->where($where)
                ->select();
		$html ='';
		$uid_arr = [];
		
		foreach($list as $key=>$value){
			$uid_arr[$value['uid']] = $key;
			$list[$key]['has_child'] = false;
			$list[$key]['date'] = date('Y-m-d H:i:s',$value['t']);
			$list[$key]['today_money'] = sprintf('%.2f', D("Income")->Income_today_count($value['uid'],$value['level']));
		}
		//查询用户是否有下级
		if(count($uid_arr)>0){
			$pid_arr = M('member')->field("count(uid) as count_pid,pid")
								  ->where("pid in(" . implode(',',array_keys($uid_arr)) . ")")
								  ->group('pid')
								  ->select();
			foreach($pid_arr as $key => $value){
				$list[$uid_arr[$value['pid']]]['has_child'] = empty($value['count_pid']) ? false : true;
			}
		}
		echo json_encode(['list' => $list,'level'=>$member_gid-$user_gid,'UserJurisdiction'=>$UserJurisdiction]);
	}
	
    public function del() {
        $uids = I("uid" , 0 , 'intval');
        if($uids == 1){
            $this->error("休想把老大干掉！！！！");
        }
        
        $rows = D("member")->delUser($uids);
        
        if($rows){
            addlog("删除会员{$uids}成功");
            $this->success("删除会员成功");
        }else{
            $this->success("删除会员失败");
        }
    }

    public function edit() {

        $uid = isset($_GET['uid']) ? intval($_GET['uid']) : false;
        if ($uid) {
            //$member = M('member')->where("uid='$uid'")->find();
            $prefix = C('DB_PREFIX');
            $user = M('member');
            $member = $user->field("{$prefix}member.*,{$prefix}auth_group_access.group_id")->join("{$prefix}auth_group_access ON {$prefix}member.uid = {$prefix}auth_group_access.uid")->where("{$prefix}member.uid=$uid")->find();
        } else {
            $this->error('参数错误！');
        }
		$user_gid=$this->USER;//获取登陆账户的权限
		/*$where = '1 = 1';//超级管理员 不能添加二级推广商
		$limit = 10;
		if($user_gid['level'] != 1){//非超级管理员 只能添加比其权限小的会员
			$where = 'id>'.$user_gid['level'];
			$limit = 1;
		}
		$limit = 1;*/
		$where = 'id>'.$user_gid['level'];
        $usergroup = M('auth_group')->field('id,title')->where($where)->order('id')->limit($limit)->select();
        $this->assign('usergroup', $usergroup);
        $this->assign('member', $member);
		//获取用户的锁定会员及其提现权限
		$this->assign('UserJurisdiction', D("member")->getUserJurisdiction(session('uid')));
		$this->assign('login_gid', $user_gid['level']);
        $this->display('form');
    }

    /**
     * 添加修改后台帐号
     * ajax 列表页修改用户的权限
     * */
    public function update($ajax = '') {
		
		if ($ajax == 'yes') {
            $uid = I('get.uid', 0, 'intval');
            $gid = I('get.gid', 0, 'intval');
			
			$user_gid=$this->USER;//获取登陆账户的权限
			if($user_gid['level'] != 1 && $user_gid['level'] >= $gid){//非管理员权限，不能添加同级及其上级
				die('0');
			}else if($user_gid['level'] == 1 && $gid == 4){//管理员权限，不能添加二级推广商
				die('0');
			}
			
			$data = [
				'level'	=> $gid
            ];
			$row = D("member")->editUser($data , $uid);
			if($row){
				M('auth_group_access')->data(array('group_id' => $gid))->where("uid='$uid'")->save();
				die('1');
			}else{
				die('0');
			}
        }
		$proportion = I("proportion" , 0 , 'intval');
        $groupid = I("group_id" , 0 , 'intval');
        $uid = I("uid" , 0 ,'intval');
        if($groupid == 0){
            $this->error("请选择用户组");
        }
		if(empty($proportion)){
			$this->error("分成比例填写错误");
		}
		if($proportion > $this->USER['proportion']){
			$this->error("分成比例不能大于自己");
		}
		if(100 < $proportion || $proportion < 10){
			$this->error("分成比例取值范围10-100");
		}
		$next_level = I('group_id' , 0 , 'intval');
		
		$member = $this->USER;//获取登陆账户的权限
		if($member['level'] >= $next_level){//不能添加同级及其上级
			$this->error('您没有权限添加此类用户');
		}
		
        $data = [
            'user'          => htmlspecialchars(I("user") , ENT_NOQUOTES),
            'phone'         => htmlspecialchars(I("phone") , ENT_NOQUOTES),
            'qq'            => htmlspecialchars(I("qq") , ENT_NOQUOTES),
            'proportion'    => I("proportion" , 0 , 'intval'),
			'account_type'  => I("account_type" , 0 , 'intval'),
            'truename'      => htmlspecialchars(I("truename") , ENT_NOQUOTES),
            'alipay'        => htmlspecialchars(I("alipay") , ENT_NOQUOTES),
			'level'			=> $next_level,
			'hierarchy'		=> I("hierarchy" , 0 , 'intval'),
        ];
		
		//设定用户是否有权禁用下级
		$if_user_lock = I('if_user_lock', 0, 'intval');
		if(!empty($if_user_lock)){
			$data['if_user_lock'] = $if_user_lock;
		}else if($member['level'] == 1 || $member['if_user_lock'] == 1){
			$data['if_user_lock'] = 2;
		}
		
		//设定用户下级是否有权提现
		$if_user_cash = I('if_user_cash', 0, 'intval');
		if(!empty($if_user_cash)){
			$data['if_user_cash'] = $if_user_cash;
		}else if($member['level'] == 1){
			$data['if_user_cash'] = 2;
		}
		
        if($uid == 0){
			if (empty($data['user'])) {
                $this->error('用户名称不能为空！');
            }
			if (empty(I("password"))) {
                $this->error('用户密码不能为空！');
            }
			
            $code = rand_stre(6);
            $data['pid']        = session("uid");                 //上级ID
            $data['password']   = password(I("password"), $code);
            $data['t']          = time();
            $data['code']       = $code;
            $data['money']      = 0 ;           //初始金额0元
            
            $newid = D("member")->addUser($data);
            if($newid == -1){
                $this->error("{$data['user']}已经存在，请换一个名称");
            }else{
                //将新户分配到指定组
                M("auth_group_access")->add(['uid' => $newid , 'group_id' => $groupid ]);
                $this->success("成功添加新的推广商" , 'index/index');
            }
        }else{
            $password = I("password" , '');
            $member = D("member")->findUser(['uid' => $uid]);
            if($password != ""){
                $data['password'] = password($password, $member['code']);
            }
            $rows = D("member")->editUser($data , $uid);
            if($rows){
				M("auth_group_access")->where('uid='.$uid)->save(['group_id' => $next_level ]);
                $this->success("编辑资料成功" , 'index/index');
            }else{
                $this->error("编辑资料失败" );
            }
        }
        
        
    }

    public function add() {
		$user_gid=$this->USER;//获取登陆账户的权限
		/*$where = 'id<>4';//超级管理员 不能添加二级推广商
		$limit = 2;
		if($user_gid['level'] != 1){//非超级管理员 只能添加比其权限小的会员
			$where = 'id>'.$user_gid['level'];
			$limit = 1;
		}*/
		$limit = 1;
		$where = 'id>'.$user_gid['level'];
        $usergroup = M('auth_group')->field('id,title')->where($where)->order('id')->limit($limit)->select();
        $this->assign('usergroup', $usergroup);
		//获取用户的锁定会员及其提现权限
		$this->assign('UserJurisdiction', D("member")->getUserJurisdiction(session('uid')));
		$this->assign('login_gid', $user_gid['level']);
        $this->display('form');
    }
	/**
	* 代理账户密码重置
	**/
	public function resetpass(){
		$ret = ['state'=>0,'msg'=>''];
		$uid = I("uid" , 0 , 'intval');
		if(empty($uid)){
			$ret['msg']='重置帐号为空';
			die(json_encode($ret));
		}
		$member = D("member")->findUser(['uid' => $uid]);
		if(empty($member)){
			$ret['msg']='重置帐号不存在';
			die(json_encode($ret));
		}
		$user_gid=$this->USER;//获取登陆账户的权限
		
		//充值密码权限  上级为下级重置 重置自己的密码   超管重置所有
		if($member['pid'] != session('uid') && $uid != session('uid') && $user_gid['level'] != 1){
			$ret['msg']='您没有权限操作';
			die(json_encode($ret));
		}
		
		// 密码字符集，可任意添加你需要的字符 
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 
		$password = ''; 
		for ( $i = 0; $i < 6; $i++ ) 
		{ 
			// 这里提供两种字符获取方式 
			// 第一种是使用 substr 截取$chars中的任意一位字符； 
			// 第二种是取字符数组 $chars 的任意元素 
			// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1); 
			$password .= $chars[ mt_rand(0, strlen($chars) - 1) ]; 
		} 
		
		$data['password'] = password($password, $member['code']);
		$rows = D("member")->editUser($data , $uid);
		
		$ret['state']=1;
		$ret['data']=$password;
		echo json_encode($ret);
	}
	/**
     *  设置代理账户是否可用
     */
    public function lock(){
		$ret = ['state'=>0,'msg'=>''];
		
        $uid = I("uid" , 0 , 'intval');
        $value = I("value" , 2 , 'intval');
		if(empty($uid)){
			$ret['msg']='操作帐号为空';
			die(json_encode($ret));
		}
		$member = D("member")->findUser(['uid' => $uid]);
		if(empty($member)){
			$ret['msg']='操作帐号不存在';
			die(json_encode($ret));
		}
        $login_user = $this->USER;//获取登陆账户的信息
		//锁定帐号权限  上级锁定下级，并且上级必须有锁定权限   超管锁定所有
		if($member['pid'] != session('uid') && ($login_user['level'] != 1 || $login_user['if_user_lock'] != 1)){
			$ret['msg']='您没有权限操作';
			die(json_encode($ret));
		}
        $row = D("member")->setLock($uid ,  $value);
        
		$ret['state']=1;
		$ret['msg']='设置成功';
		echo json_encode($ret);
    }
}
